package mall

import (
	"context"
	"fmt"
	"github.com/shopspring/decimal"
	"private-domain-overseas-service/admin/business/api/internal/repository/mall"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MallGoodsEditLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 添加/编辑推荐商品
func NewMallGoodsEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MallGoodsEditLogic {
	return &MallGoodsEditLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MallGoodsEditLogic) MallGoodsEdit(req *types.MallGoodsEditReqeust) error {
	goodsDao := mall.NewMallGoodsDao(l.ctx, l.svcCtx)

	//定义百初始值
	baiDecimal := decimal.NewFromInt(100)
	//处理商品的添加时间
	goodsCreatedAt, _ := time.Parse(time.DateTime, req.GoodsCreatedAt)
	//商品原价
	goodsOriginalPriceYuan, _ := decimal.NewFromString(req.GoodsOriginalPrice)
	//商品到手价
	goodsReceivedPriceYuan, _ := decimal.NewFromString(req.GoodsReceivedPrice)
	//商品佣金比例
	goodsCommissionRate, _ := decimal.NewFromString(req.GoodsCommissionRate)
	//商品佣金
	goodsCommissionYuan, _ := decimal.NewFromString(req.GoodsCommission)

	hzMallGoods := &ent.HzMallGoods{
		GoodsCreatedAt:      goodsCreatedAt.Unix(),
		GoodsTitle:          req.GoodsTitle,
		GoodsOriginalPrice:  goodsOriginalPriceYuan.Mul(baiDecimal).IntPart(),
		GoodsReceivedPrice:  goodsReceivedPriceYuan.Mul(baiDecimal).IntPart(),
		GoodsCommissionRate: goodsCommissionRate.Mul(baiDecimal).IntPart(),
		GoodsCommission:     goodsCommissionYuan.Mul(baiDecimal).IntPart(),
		GoodsMallID:         req.GoodsMallId,
		GoodsBuyURL:         req.GoodsBuyUrl,
		GoodsImage:          req.GoodsImage,
		GoodsDesc:           req.GoodsDesc,
		GoodsStatus:         req.GoodsStatus,
		CreatedAt:           time.Now().Unix(),
		UpdateAt:            time.Now().Unix(),
	}

	//添加
	if req.Type == "add" {
		_, err := goodsDao.MallGoodsCreate(hzMallGoods, nil)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("添加推荐商品失败：%v", err))
		}
	}
	
	//编辑
	if req.Type == "edit" {
		hzMallGoods.ID = int(req.Id)
		_, err := goodsDao.MallGoodsUpdate(hzMallGoods, nil)
		if err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("编辑推荐商品失败：%v", err))
		}
	}
	return nil
}
